package com.lwl.blue.commont.base;

import com.lwl.blue.commont.aop.PowerFieldInterface;
import com.lwl.blue.commont.enums.PowerDataTypeEnum;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.vo.LoginUserInfo;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

public class BaseController {

    public LoginUserInfo getUserInfo() {
        return UserContextUtil.getUser();
    }

    public void setInsetOrUpdateUser(BaseEntity baseEntity) {
        LoginUserInfo user = UserContextUtil.getUser();
        baseEntity.setCreateUser(user.getUserName());
        baseEntity.setCreateTime(new Date());
        baseEntity.setUpdateUser(user.getUserName());
        baseEntity.setUpdateTime(new Date());
        baseEntity.setIsDelete(0);
        //忽略属性的访问权限  修改权限的控制，将数据变成NULL
        Class aClass = baseEntity.getClass();
        Field[] declaredFields = baseEntity.getClass().getDeclaredFields();
        if (PowerDataTypeEnum.EDIT.getValue() == user.getPowerDataType()) {
            return;
        }
        for (Field f : declaredFields) {
            boolean annotation = f.isAnnotationPresent(PowerFieldInterface.class);
            if (annotation) {
                try {
                    f.setAccessible(true);
                    String name = f.getName();
                    Class type = f.getType();
                    Method method = aClass.getMethod("set" + name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase()),
                            type);
                    method.invoke(baseEntity, new Object[]{null});
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
